package com.by.hellofreemarker.controller;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/file")
public class FileController {

    @Resource
    private Configuration configuration;

    @GetMapping("/export")
    public String export() {
        try {
            Map<String, Object> export = new HashMap<>();
            export.put("classPath", "com.by.test");
            export.put("className", "ExportTest");
            export.put("helloWorld", "Hello World!");
            Template template = configuration.getTemplate("file.ftl");
            File file = new File("ExportTest.java");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
            template.process(export, out);
            out.close();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            return "生成失败";
        }

        return "生成成功";
    }

}
